<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../../static/lib/layui-v2.9.8/css/layui.css" media="all">
    <link rel="stylesheet" href="./../../static/css/public.css" media="all">
    <style>
        .layui-table-cell {
            height: auto !important;
            overflow: visible !important;
            text-overflow: inherit !important;
            white-space: normal !important;
            word-break: break-all !important;
        }
    </style>
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">
        <fieldset class="table-search-fieldset">
            <legend>查询条件</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">装备器材名字</label>
                            <div class="layui-input-inline">
                                <input type="text" name="name" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">规格</label>
                            <div class="layui-input-inline">
                                <input type="text" name="specification" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        {% if request.session.role_id == 1 %}
                        <div class="layui-inline">
                            <label class="layui-form-label required">库房名字</label>
                            <div class="layui-input-inline">
                                <select name="fk_department" lay-search="" lay-verify="fk_department">
                                    <option value="">选择库房名字</option>
                                    {% for item in departments %}
                                    <option value="{{ item.pk }}">{{ item.name }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                        {% endif %}
                        <div class="layui-inline">

                            <button type="submit" class="layui-btn layui-btn-normal" lay-submit
                                    lay-filter="data-search-btn"><i class="layui-icon"></i> 查 询
                            </button>


                            <button type="reset" class="layui-btn layui-btn-primary"><i
                                    class="layui-icon layui-icon-refresh"></i> 重 置
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-primary layui-border-green layui-btn-xs data-count-edit"
               lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-xs layui-btn-primary layui-border-red data-count-delete"
               lay-event="delete">删除</a>
        </script>
        <script type="text/html" id="toolbarUser">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-primary layui-border-green layui-btn-sm data-add-btn"
                        lay-event="add"> 新增
                </button>
                <button class="layui-btn layui-btn-sm layui-btn-primary layui-border-red data-delete-btn"
                        lay-event="batch_delete"> 批量删除
                </button>
            </div>
        </script>
    </div>
</div>
<script src="../../../static/lib/layui-v2.9.8/layui.js" charset="utf-8"></script>
<script>
    layui.use(['form', 'table', 'util'], function () {
                var $ = layui.jquery,
                        form = layui.form,
                        util = layui.util,
                        table = layui.table;

                var userID = $("#login_user", parent.document).text();

                var token = "{{ csrf_token }}"
                $.ajaxSetup({
                    headers: {
                        'X-CSRFTOKEN': `${token}`,
                        'AUTHORIZATION': 'Bearer ' + localStorage.token,
                    }, // JWTAuthentication.authenticate()方法获取 header = request.META.get(api_settings.AUTH_HEADER_NAME),
                });


                $.ajaxSetup({
                    complete: function (XMLHttpRequest, textStatus) {
                        if (XMLHttpRequest.status === 401) {  // 401 表示未授权，即 token 无效
                            layer.msg('授权已过期，需重新登陆', {icon: 2, time: 2000}, function () {
                                window.location.href = '/login';
                            })
                        }
                    }
                });

                window.parent_msg = function (msg) {
                    layer.msg(msg, {icon: 1})
                }

                table.render({
                    elem: '#currentTableId',
                    url: '/product_manage_list/',
                    method: 'get',
                    toolbar: '#toolbarUser',
                    defaultToolbar: ['filter', 'exports', 'print'],
                    cellMinWidth: 90,
                    cols: [[
                        {type: "checkbox", width: 50},
                        {field: 'count', width: 100, title: '序号', align: 'center', sort: true, type: 'numbers'},
                        {field: 'id', title: 'ID', align: 'center', hide: true},
                        {field: 'name', width: 150,title: '装备器材名称', align: 'center'},
                        {field: 'department_name', title: '库房名字', align: 'center'},
                        {field: 'specification', title: '规格', align: 'center'},
                        {field: 'price', title: '价格', align: 'center'},
                        {field: 'quantity', title: '数量', align: 'center'},
                        {field: 'classification', title: '分类', align: 'center'},
                        {field: 'manage_unit', title: '管理单位', align: 'center'},
                        {field: 'person', title: '责任人', align: 'center'},
                        {field: 'unit', title: '计量单位', align: 'center'},
                        {field: 'user_year', title: '使用期限', align: 'center'},
                        {field: 'stay_year', title: '存储期限', align: 'center'},
                        {field: 'quality_grade', title: '质量等级', align: 'center'},
                        {
                            title: '装备器材图片', align: 'center', width: 160, templet: function (d) {
                                let img_tag = '<div lay-on="test-tips-photos">'
                                if (d.fk_product_to_product_upload_image_set.length === 0) {
                                    return img_tag;
                                }
                                $.each(d.fk_product_to_product_upload_image_set, function (index, item) {
                                    img_tag += '<img src="/product_manage_img?id=' + item['id'] + '&fk_product=' + item['fk_product'] + '" alt="product_img" height="100px">'
                                })
                                return img_tag + '</div>';
                            }
                        },
                        {
                            title: '产品条形码', align: 'center', width: 160, templet: function (d) {
                                return '<img src="/product_manage_code?id=' + d.id + '" alt="code_img" height="100px">'
                            }
                        },
                        {field: 'other', title: '备注', align: 'center'},
                        {
                            title: '操作',
                            minWidth: 200,
                            toolbar: '#currentTableBar',
                            align: "center",
                            fixed: 'right'
                        }
                    ]],
                    limits: [10, 15, 20, 25, 50, 100],
                    limit: 10,
                    page: true,
                    skin: 'grid',
                    even: false,
                    parseData: function (res) { //res 即为原始返回的数据
                        console.log(res)
                    },
                    before: function (res, curr, count) {
                    },
                    done: function (res, curr, count) {
                        util.on('lay-on', {
                            'test-tips-photos': function () {
                                let data_list = []
                                $.each($(this).find('img'), function (index, img_obj) {
                                    let item = {
                                        'src': $(img_obj).attr('src'),
                                        'alt': $(img_obj).attr('alt')
                                    }
                                    data_list.push(item)
                                })
                                layer.photos({
                                    photos: {
                                        "title": "Photos Demo",
                                        "start": 0,
                                        "data": data_list
                                    }
                                });
                            }
                        })


                        $(".layui-table-main tbody tr").each(function (index, val) {
                            let img_length_list = []
                            $.each($(val).find('td'), function (index, td_obj) {
                                if ($(td_obj).find('img').length === 0) {
                                    return true;
                                }
                                img_length_list.push($(td_obj).find('img').length)
                            })
                            let img_count = Math.max(...Array.from(new Set(img_length_list)))
                            if (img_count === 0) {
                                $($(".layui-table-fixed-r .layui-table-body tbody tr")[index]).height($(val).height());
                                $($(".layui-table-fixed-l .layui-table-body tbody tr")[index]).height($(val).height());
                            } else {
                                $($(".layui-table-fixed-r .layui-table-body tbody tr")[index]).height(13 + $(val).find('img').height() * img_count);
                                $($(".layui-table-fixed-l .layui-table-body tbody tr")[index]).height(13 + $(val).find('img').height() * img_count);
                            }
                        });
                    }

                });

                // 监听搜索操作
                form.on('submit(data-search-btn)', function (data) {
                    console.log(data.field);
                    var result = JSON.stringify(data.field);

                    //执行搜索重载
                    table.reload('currentTableId', {
                        page: {
                            curr: 1
                        }
                        , where: {
                            Params: result
                        }
                    }, 'data');

                    return false;
                });

                /**
                 * toolbar监听事件
                 */
                table.on('toolbar(currentTableFilter)', function (obj) {
                    if (obj.event === 'add') {  // 监听添加操作
                        var index = layer.open({
                            title: '新增装备器材',
                            type: 2,
                            shade: 0.2,
                            maxmin: true,
                            shadeClose: true,
                            area: ['100%', '100%'],
                            content: '/product_manage_add',
                        });
                        $(window).on("resize", function () {
                            layer.full(index);
                        });
                    } else if (obj.event === 'batch_delete') {
                        let checkStatus = table.checkStatus('currentTableId')
                        if (checkStatus.data.length === 0) {
                            layer.msg('没有选择删除数据')
                            return false;
                        }
                        layer.confirm('真的删除行么?', {icon: 3, title: '确认删除'}, function (index) {
                            layer.close(index);
                            $.ajax({
                                url: '/product_manage_list/multiple_delete/',
                                type: "delete",
                                data: {Params: JSON.stringify(checkStatus.data)},
                                success: function (result) {
                                    if (result.success) {
                                        layer.msg(result.msg, {icon: 1});
                                        table.reload('currentTableId')
                                    } else {
                                        layer.msg(result.msg, {icon: 2});
                                    }
                                },
                                error: function (result) {
                                    alert("接口错误！！");
                                }
                            });
                            table.reload('currentTableId')
                            return false;
                        });
                    }
                })
                //监听表格复选框选择
                table.on('checkbox(currentTableFilter)', function (obj) {
                    console.log(obj)
                });

                table.on('tool(currentTableFilter)', function (obj) {
                    var data = obj.data;
                    if (obj.event === 'edit') {
                        var index = layer.open({
                            title: '编辑装备器材',
                            type: 2,
                            shade: 0.2,
                            maxmin: true,
                            shadeClose: true,
                            area: ['100%', '100%'],
                            content: '/product_manage_edit',
                            success: function (layero, index) {
                                let iframe = window['layui-layer-iframe' + index];
                                iframe.parent_to_child(obj);
                            }
                        });
                        $(window).on("resize", function () {
                        });
                        return false;
                    } else if (obj.event === 'delete') {
                        layer.confirm('真的删除行么?', {icon: 3, title: '确认删除'}, function (index) {
                            obj.del();
                            layer.close(index);
                            $.ajax({
                                url: '/product_manage_list/' + obj.data.id + '/',
                                type: "delete",
                                data: obj.data,
                                success: function (result) {
                                    if (result.success) {
                                        layer.msg(result.msg, {icon: 1});
                                    } else {
                                        layer.msg(result.msg, {icon: 2});
                                    }
                                },
                                error: function (result) {
                                    alert("接口错误！！");
                                }
                            });
                            return false;
                        });
                    }
                });


                table.on('edit(currentTableFilter)', function (obj) { //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
                    // console.log(obj.value); //得到修改后的值
                    // console.log(obj.field); //当前编辑的字段名
                    console.log(obj.data); //所在行的所有相关数据
                    //传给后台
                    var URL = '/role/' + obj.data.id + '/';
                    $.ajax({
                        url: URL,
                        type: "put",
                        data: obj.data,
                        success: function (result) {
                            if (result.success) {
                                layer.msg(result.msg, {icon: 1});
                            } else {
                                layer.msg(result.msg, {icon: 2});
                            }

                        },
                        error: function (result) {
                            alert("接口错误！！");
                        }
                    });
                    return false;


                });

                // 监听开关
                form.on('switch(role-enable)', function (obj) {
                    // console.log(obj.elem.attributes['roleID'].nodeValue);
                    // console.log(obj);
                    let roleId = obj.elem.attributes['roleID'].nodeValue;

                    let operate
                    if (obj.elem.checked) {
                        operate = 'enable'
                    } else {
                        operate = 'disable'
                    }
                    let loading = layer.load()

                    $.ajax({
                        url: "/role/enable/",
                        type: "put",
                        data: {
                            id: roleId,
                            enable: operate
                        },
                        success: function (result) {
                            layer.close(loading)
                            if (result.success) {
                                layer.msg(result.msg, {icon: 1});
                            } else {
                                layer.msg(result.msg, {icon: 2});
                            }
                        },
                        error: function (result) {
                            alert("接口错误！！");
                        }
                    });
                    return false;

                })
                // window.refresh = function (param) {
                //   table.reload('currentTableId', { where: params })
                // }
            });
</script>

</body>
</html>